package com.darren.center.design.patterns.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <h3>design-patterns</h3>
 * <p></p>
 *
 * @author : Darren
 * @date : 2021年06月14日 19:36:51
 **/
public class HtmlUtil {

    private static final Logger logger = LoggerFactory.getLogger(HtmlUtil.class);
    public final static String ATTR_JSON_OBJECT = "com.gzhc365.web.json.obj";

    public static void writerJson(HttpServletResponse response, Object object) {
        response.setContentType("application/json");
        String json = JSON.toJSONString(object);
        logger.info("Response" + json);
        writer(response, json);
    }

    public static void writerCustomize(HttpServletResponse response, String data,String contextType) {
        response.setContentType(contextType==null?"application/json":contextType);
        logger.info("Response" + data);
        writer(response, data);
    }

    private static void writer(HttpServletResponse response, String str) {
        try {
            // 设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

